﻿using System.Collections;
using UnityEngine;

namespace XLua_Ki
{
    /// 加载3D_GameObject
    public class ObjectManager_Ki : MonoBehaviour
    {
        public void CreateObject(string name, Transform parent = null, XLua.LuaFunction luaFunction = null)
        {
            StartCoroutine(OnCreateObject(name, parent, luaFunction));
        }

        IEnumerator OnCreateObject(string name, Transform parent, XLua.LuaFunction luaFunction)
        {
            var assetName = name.ToLower();
            GameObject go = null;
            GameObject obj = null;

            if (GameManager_Ki.Instance.GetResourcesManager_Ki().Prefabs_AB_GAME.TryGetValue(assetName, out go))
            {
                //..
            }
            else
            {
                AssetBundle ab = null;
                var bundleName = BundleRequest.MatchBundleName(name); //通过name找到对应的Bundle
                if (GameManager_Ki.Instance.GetResourcesManager_Ki().Bundles_AB_GAME.TryGetValue(bundleName, out ab))
                {
                    var request = ab.LoadAssetAsync<GameObject>(name);
                    yield return request;
                    if (request.isDone)
                    {
                        go = request.asset as GameObject;
                    }
                }
            }

            obj = GameManager_Ki.Instance.GetPoolManager_Ki().ReturnScence(go, parent);
            if (parent == null)
            {
                obj.transform.localScale = Vector3.one;
                obj.transform.position = Vector3.zero;
            }

            yield return null;
            if (luaFunction != null) luaFunction.Call(obj);
        }
    }
}
